#!/usr/bin/env bash
#
# Summary: Run an executable with the selected Java version
#
# Usage: jenv exec <command> [arg1 arg2...]
#
# Runs an executable by first preparing PATH so that the selected Java
# version's `bin' directory is at the front.
#
# For example, if the currently selected Java version is oracle-1.6.3:
#   jenv exec java -jar myjar.jar
#
# is equivalent to:
#   PATH="$JENV_ROOT/versions/oracle-1.6.3/bin:$PATH" java -jar myjar.jar

set -e
[ -n "$JENV_DEBUG" ] && set -x

exportVariable(){
   exportedValues="$exportedValues:$1"
   export "$1"="$2"
}

# Provide jenv completions
if [ "$1" = "--complete" ]; then
  exec jenv shims --short
fi

export JENV_VERSION="$(jenv-version-name)"
JENV_COMMAND="$1"

export JENV_OPTIONS="$(jenv-options)"

if [ "$JENV_VERSION" != "system" ]; then
  export JAVA_HOME="$JENV_ROOT/versions/$JENV_VERSION"
fi

if [ -z "$JENV_COMMAND" ]; then
  jenv-help --usage exec >&2
  exit 1
fi

JENV_COMMAND_PATH="$(jenv-which "$JENV_COMMAND")"
JENV_BIN_PATH="${JENV_COMMAND_PATH%/*}"

for script in $(jenv-hooks exec); do

source "$script"
done

shift 1
if [ "$JENV_VERSION" != "system" ]; then
  export PATH="${JENV_BIN_PATH}:${PATH}"
fi
exec -a "$JENV_COMMAND" "$JENV_COMMAND_PATH" $JENV_OPTIONS "$@"
